package chapter2;

import java.util.*;


/**
 * 种群
 */
public class Population {
    //个体列表
    private List<Individual> individualList;
    //种群适应度
    private double populationFitness = -1;

    /**
     * 初始化空种群
     *
     * @param populationSize 种群大小 种群的个体数
     */
    public Population(int populationSize) {
        // 初始化空种群
        this.individualList = new ArrayList<>();
    }

    /**
     * 初始化种群里的个体
     *
     * @param populationSize   种群大小
     * @param chromosomeLength 每个个体染色体长度
     */
    public Population(int populationSize, int chromosomeLength) {
        // 初始化种群数组
        this.individualList = new ArrayList<>();

        // 循环创建个体
        for (int individualCount = 0; individualCount < populationSize; individualCount++) {
            // 根据给定的染色体长度创建个体
            Individual individual = new Individual(chromosomeLength);
            // 将个体加入到种群
            this.individualList.add(individual);
        }
    }

    /**
     * 获取个体列表
     *
     * @return individuals 种群的个体
     */
    public List<Individual> getIndividuals() {
        return this.individualList;
    }

    /**
     * 获取按适应度排序后指定位置的个体
     *
     * @param offset 获取按适应度排序后指定位置，大的排前面
     * @return individual Individual at offset
     */
    public Individual getFittest(int offset) {
        // 对适应的排序，大的排前面
        Collections.sort(this.individualList, new Comparator<Individual>() {
            @Override
            public int compare(Individual o1, Individual o2) {
                if (o1.getFitness() > o2.getFitness()) {
                    return -1;
                } else if (o1.getFitness() < o2.getFitness()) {
                    return 1;
                }
                return 0;
            }
        });
        // 返回指定位置的个体
        return this.individualList.get(offset);
    }


    public void setPopulationFitness(double fitness) {
        this.populationFitness = fitness;
    }


    public double getPopulationFitness() {
        return this.populationFitness;
    }

    /**
     * 获取种群大小
     *
     * @return size 种群大小
     */
    public int size() {
        return this.individualList.size();
    }


    /**
     * 种群添加个体
     *
     * @param individual
     * @return void
     */
    public void addIndividual(Individual individual) {
        individualList.add(individual);
    }

    /**
     * 获取指定位置个体
     *
     * @param offset
     * @return individual
     */
    public Individual getIndividual(int offset) {
        return individualList.get(offset);
    }

    /**
     * 打乱个体顺序
     *
     * @param
     * @return void
     */
    public void shuffle() {
        Random rnd = new Random();
        for (int i = individualList.size() - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            Individual a = individualList.get(index);
            individualList.set(index, individualList.get(i));
            individualList.set(i, a);
        }
    }
}